package com.lyfei.yd.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lyfei.yd.domain.entity.SimplifySpu;
import com.lyfei.yd.domain.entity.Spu;
import com.lyfei.yd.domain.entity.Theme;
import com.lyfei.yd.domain.entity.ThemeSpu;
import com.lyfei.yd.mapper.ThemeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service("themeService")
public class ThemeService extends BaseService<ThemeMapper, Theme> {
    @Autowired
    private ThemeSpuService themeSpuService;

    @Autowired
    private SpuService spuService;

    public List<SimplifySpu> getSpuListByThemeId(Long themeId) {
        List<ThemeSpu> themeSpuList = themeSpuService.list(new LambdaQueryWrapper<ThemeSpu>()
                .eq(ThemeSpu::getThemeId, themeId));

        List<SimplifySpu> results = new ArrayList<>();
        themeSpuList.forEach(item -> {
            SimplifySpu simplifySpu = new SimplifySpu();
            simplifySpu.setSpuId(item.getSpuId());
            simplifySpu.setThemeSpuId(item.getId());

            Spu spu = spuService.getById(item.getSpuId());
            simplifySpu.setTitle(spu.getTitle());
            simplifySpu.setSubtitle(spu.getSubTitle());
            simplifySpu.setImg(spu.getImg());
            results.add(simplifySpu);
        });

        return results;
    }


    /**
     * 获取某主题下可选的spu列表
     * @param themeId 主题id
     * @return spu列表
     */
    public List<Spu> getAvailableSpuList(Long themeId) {
        List<Spu> spuList = spuService.list(new LambdaQueryWrapper<Spu>()
                .eq(Spu::getDeleted, false));

        List<ThemeSpu> themeSpuList = themeSpuService.list(new LambdaQueryWrapper<ThemeSpu>()
                .eq(ThemeSpu::getThemeId, themeId));

        return spuList.stream()
                .filter(spu -> themeSpuList.stream()
                        .noneMatch(themeSpu -> themeSpu.getSpuId().equals(spu.getId())))
                .collect(Collectors.toList());
    }

    public List<Spu> getSpuListByThemeName(String name) {
        Theme theme = this.getOne(new LambdaQueryWrapper<Theme>().eq(Theme::getName, name)
                .eq(Theme::getDeleted, false));
        if(theme == null) {
            return new ArrayList<>();
        }

        List<ThemeSpu> themeSpuList = themeSpuService.list(new LambdaQueryWrapper<ThemeSpu>()
                .eq(ThemeSpu::getThemeId, theme.getId()));
        if(themeSpuList == null || themeSpuList.isEmpty()){
            return new ArrayList<>();
        }


        return spuService.listByIds(themeSpuList.stream()
                .map(ThemeSpu::getSpuId).collect(Collectors.toList()));
    }
}
